<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区域 -->
        <el-card class="box-card">
            <el-row :gutter="20">
                <el-col :span="8">
                    <!-- 搜索框 -->
                    <el-input placeholder="请输入搜索的内容" v-model="queryInfo.query" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <!-- 按钮 -->
                    <el-button type="primary" @click="addDialogVisible= true">添加用户</el-button>
                </el-col>
            </el-row>
            <!-- 表格区域 -->
            <el-table :data="userList" border stripe>
                <!-- type="index"设置当前列为索引列 -->
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="username" label="姓名"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="mobile" label="电话"></el-table-column>
                <el-table-column prop="role_name" label="角色"></el-table-column>
                <el-table-column label="状态">
                    <!-- 使用作用域插槽 -->
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" @change='updateUserState(scope.row)'>
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作"  width="180px">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
                        <!-- enterable，鼠标是否可进入到 tooltip 中，默认true -->
                        <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页区域 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[2, 3, 4, 5]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card>
        <!-- 添加用户对话框区域 -->
        <el-dialog
            title="提示"
            :visible.sync="addDialogVisible"
            @close="addDialogClosed">
            <!-- 内容主体区域 -->
            <el-form :model="addUserForm" :rules="addUserRules" ref="addUserRef" label-width="70px">
                <el-form-item label="用户名">
                    <el-input prefix-icon="iconfont icon-user" v-model="addUserForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input prefix-icon="iconfont icon-3702mima" v-model="addUserForm.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input prefix-icon="el-icon-email" v-model="addUserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input prefix-icon="el-icon-mobile" v-model="addUserForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改用户对话框区域 -->
        <el-dialog
            title="提示"
            :visible.sync="editDialogVisible"
            @close="editDialogClosed">
            <!-- 内容主体区域 -->
            <el-form :model="editUserForm" :rules="editUserRules" ref="editUserRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input prefix-icon="iconfont icon-user" v-model="editUserForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input prefix-icon="el-icon-email" v-model="editUserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input prefix-icon="el-icon-mobile" v-model="editUserForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUser">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data() {
        // 自定义校验规则
        var checkEmail = (rule, value, cb) => {
                const regEmail = /^\w+@\w+(\.\w+)+$/
                if (regEmail.test(value)) return cb()
                cb(new Error("邮箱格式错误"))
            }
        var checkMobile = (rule, value, cb) => {
            const regMobile = /^1[34578]\d{9}$/
            if (regMobile.test(value)) return cb()
            cb(new Error("手机号格式错误"))
        }
        return {
            // 用户数据列表参数对象
            queryInfo : {
                query : '',
                pagenum : 1,
                pagesize : 2
            },
            // 响应参数
            userList : [],
            total: 0,
            // 设置对话框的显示true和隐藏false
            addDialogVisible: false,
            addUserForm: {
                username: '',
                password:'',
                email: '',
                mobile: '',
            },
            addUserRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    {validator : checkEmail, message: '邮箱格式不正确，请重新输入', trigger: 'blur'}
                ],
                mobile: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    {validator : checkMobile, message: '手机号格式不正确，请重新输入', trigger: 'blur'}
                ]
            },
            editDialogVisible: false,
            editUserForm: {},
            editUserRules: {
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    {validator : checkEmail, message: '邮箱格式不正确，请重新输入', trigger: 'blur'}
                ],
                mobile: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    {validator : checkMobile, message: '手机号格式不正确，请重新输入', trigger: 'blur'}
                ]
            },
        }
    },
    created() {
        this.getUserList()
    },
    methods: {
        async getUserList() {
            const {data: res} = await this.$http.get('/users',{
                params: this.queryInfo
            });
            console.log(res)
            if (res.meta.status != 200) return this.$message.error(res.meta.msg)
            this.userList = res.data.users
            this.total = res.data.total
        },
        //获取当前的页数
        handleSizeChange(newSize) {
            console.log(newSize)
            this.queryInfo.pagesize = newSize
            this.getUserList()
        },
        // 获取当前页
        handleCurrentChange(newPage) {
            console.log(newPage)
            this.queryInfo.pagenum = newPage
            this.getUserList()
        },
        // 修改用户状态
        async updateUserState(userInfo) {
            console.log(userInfo)
            //拼接字符串可以用模板字符串
            const {data: res} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
            if (res.meta.status != 200) {
                this.$message.error(res.meta.msg)
                //修改回原来的状态
                userInfo.mg_state = !userInfo.mg_state
            }
            this.$message.success(res.meta.msg)
        },
        // 清空对话框
        addDialogClosed() {
            this.$refs.addUserRef.resetFields()
        },
        // 添加用户
        addUser() {
            this.$refs.addUserRef.validate(async valid => {
                console.log(valid)
                if (!valid) return
                const {data: res} = await this.$http.post('users',this.addUserForm)
                if(res.meta.status != 201) return this.$message.error(res.meta.msg)
                this.$message.success(res.meta.msg)
                this.addDialogVisible = false
                this.getUserList()
            })
        },
        // 显示编辑用户对话框
        async showEditDialog(id) {
            const {data: res} = await this.$http.get('users/' + id)
            if (res.meta.status != 200) {
                this.$message.error(res.meta.msg)
            }
            this.editUserForm = res.data
            console.log(this.editUserForm);
            this.editDialogVisible = true
        },
        editDialogClosed() {
            this.$refs.addUserRef.resetFields()
        },
        // 修改用户
        editUser() {
            //用户点击修改表单中的确定按钮之后，验证表单数据
            this.$refs.editUserRef.validate(async valid => {
            if (!valid) return this.$message.error('请填写完整用户信息')
            //发送请求完成修改用户的操作
            const { data: res } = await this.$http.put(
                'users/' + this.editUserForm.id,
                this.editUserForm
            )
            //判断如果修改失败，就做提示
            if (res.meta.status !== 200) return this.$message.error('修改用户失败')
            //修改成功的提示
            this.$message.success('修改用户成功')
            //关闭对话框
            this.editDialogVisible = false
            //重新请求最新的数据
            this.getUserList()
            })
        },
        // 删除用户
        async removeUserById(id){
            //弹出确定取消框，是否删除用户
            const confirmResult = await this.$confirm('请问是否要永久删除该用户','删除提示',{
            confirmButtonText:'确认删除',
            cancelButtonText:'取消',
            type:'warning'
            }).catch(err=>err)
            //如果用户点击确认，则confirmResult 为'confirm'
            //如果用户点击取消, 则confirmResult获取的就是catch的错误消息'cancel'
            if(confirmResult != "confirm"){
                return this.$message.info("已经取消删除")
            }
            //发送请求根据id完成删除操作
            const {data:res} = await this.$http.delete('users/'+id)
            //判断如果删除失败，就做提示
            if (res.meta.status !== 200) return this.$message.error('删除用户失败')
            //修改成功的提示
            this.$message.success('删除用户成功')
            //重新请求最新的数据
            this.getUserList()
        }
    }
}
</script>